<?php
namespace app\mp\admin;
use app\system\admin\Admin;
use app\common\model\Tags as TagsModel;
use app\common\model\Factory as FactoryModel;
use think\Db;

class Tags extends Admin
{
    protected $hisiModel = 'Tags';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'Tags';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();
    }

    public function index()
    {
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$keyword    = $this->request->param('keyword/s');

    		if ($keyword) {
    			$where[] = ['name', 'like', "%{$keyword}%"];
    		}

    		$order = 'id desc';
    		$list = TagsModel::where($where)->page($page)->limit($limit)->order($order)->select();

            $factoryList = FactoryModel::where(['status'=>1])->field('id,name')->column('name','id');
            foreach ($list as $k => $v) {
                $weightConfig = $v['weight_config']??[];
                $weightArr = empty($weightConfig)?[]:json_decode($weightConfig, true);
                $weightArrTmp = [];
                foreach ($weightArr as $sk => $sv) {
                	$weightArrTmp[] = arrayGet($factoryList, $sk, '')."（<span class='red'>{$sv}</span>）";
                }
                $list[$k]['weight'] = implode(' : ', $weightArrTmp);
            }
            $data['data'] = $list;
    		$data['count'] = TagsModel::where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    /**
     * [通用方法]添加页面展示和保存
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $postData = $this->request->post();

            $weight = $postData['weight'] ?? [];
            $postData['weight_config'] = json_encode($postData['weight']);
            $rateConfig = [];
            $rateBase = array_sum($weight);
            foreach ($weight as $k => $v) {
                $rateConfig[$k] = $rateBase ? round($v/$rateBase, 2) : 0;
            }
            $postData['rate_config'] = json_encode($rateConfig);

            if ($this->hisiValidate) {// 数据验证

                if (strpos($this->hisiValidate, '\\') === false ) {

                    if (defined('IS_PLUGINS')) {
                        $this->hisiValidate = 'plugins\\'.$this->request->param('_p').'\\validate\\'.$this->hisiValidate;
                    } else {
                        $this->hisiValidate = 'app\\'.$this->request->module().'\\validate\\'.$this->hisiValidate;
                    }

                }

                if ($this->hisiAddScene) {
                    $this->hisiValidate = $this->hisiValidate.'.'.$this->hisiAddScene;
                }

                $result = $this->validate($postData, $this->hisiValidate);
                if ($result !== true) {
                    return $this->error($result);
                }

            }

            if ($this->hisiModel) {// 通过Model添加

                $model = $this->model();

                if (!$model->save($postData)) {
                    return $this->error($model->getError());
                }

            } else if ($this->hisiTable) {// 通过Db添加

                if (!Db::name($this->hisiTable)->insert($postData)) {
                    return $this->error('保存失败');
                }

            } else {

                return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');

            }

            return $this->success('保存成功', '');
        }

        $template = $this->request->param('template', 'form');
        $factoryList = FactoryModel::where(['status'=>1])->field('id,name')->column('name','id');
        $this->assign('factoryList',$factoryList);
        return $this->fetch($template);
    }

    /**
     * [通用方法]编辑页面展示和保存
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();

            $weight = $postData['weight'] ?? [];
            $postData['weight_config'] = json_encode($postData['weight']);
            $rateConfig = [];
            $rateBase = array_sum($weight);
            foreach ($weight as $k => $v) {
                $rateConfig[$k] = $rateBase ? round($v/$rateBase, 2) : 0;
            }
            $postData['rate_config'] = json_encode($rateConfig);

            if ($this->hisiValidate) {

                if (strpos($this->hisiValidate, '\\') === false ) {

                    if (defined('IS_PLUGINS')) {
                        $this->hisiValidate = 'plugins\\'.$this->request->param('_p').'\\validate\\'.$this->hisiValidate;
                    } else {
                        $this->hisiValidate = 'app\\'.$this->request->module().'\\validate\\'.$this->hisiValidate;
                    }

                }

                if ($this->hisiEditScene) {
                    $this->hisiValidate = $this->hisiValidate.'.'.$this->hisiEditScene;
                }

                $result = $this->validate($postData, $this->hisiValidate);
                if ($result !== true) {
                    return $this->error($result);
                }

            }
        }

        $where = [];
        if ($this->hisiModel) {// 通过Model更新

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {

                if ($model->save($postData, $where) === false) {
                    return $this->error($model->getError());
                }

                return $this->success('保存成功', '');
            }

            $formData = $model->where($where)->find();

        } else if ($this->hisiTable) {// 通过Db更新

            $db = Db::name($this->hisiTable);
            $pk = $db->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {

                if (!$db->where($where)->update($postData)) {
                    return $this->error('保存失败');
                }

                return $this->success('保存成功', '');
            }

            $formData = $db->where($where)->find();

        } else {

            return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');

        }

        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }
        $formData['weight_config'] = json_decode($formData->weight_config??'',true);
        $this->assign('formData', $formData);

        $template = $this->request->param('template', 'form');

        $factoryList = FactoryModel::where(['status'=>1])->field('id,name')->column('name','id');
        $this->assign('factoryList',$factoryList);
        return $this->fetch($template);
    }
}